//
//  AddViewController.m
//  植物管理
//
//  Created by liujianlong on 2022/11/21.
//

#import "AddViewController.h"
#import "AddCell.h"
#import "ContentCell.h"
#import "NongViewController.h"

@interface AddViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) NSArray *array;
@end

@implementation AddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (void)initUI{
    self.title = LS(@"添加");
    [self.rightBtn setTitle:LS(@"保存") forState:UIControlStateNormal];
    [self.rightBtn setTitleColor:[@"#3E6F51" color] forState:UIControlStateNormal];
    self.array = @[@"植物",@"数量",@"记农事",@"简介信息",@"种植时间"];
    self.tableView.c_edges.equalTo(self.view);
    [self.tableView registerNib:[AddCell nib] forCellReuseIdentifier:[AddCell ID]];
    [self.tableView registerNib:[ContentCell nib] forCellReuseIdentifier:[ContentCell ID]];
}

- (void)rightBtnAction{
    if (self.model.plant.length <= 0) {
        return [CCHud msg:LS(@"植物名称不能为空")];
    }else if (self.model.num.length <= 0){
        return [CCHud msg:LS(@"数量不能为空")];
    }else if (self.model.job.length <= 0){
        return [CCHud msg:LS(@"农事内容不能为空")];
    }else if (self.model.remark.length <= 0){
        return [CCHud msg:LS(@"备注不能为空")];
    }else if (self.model.imgs.count <= 0){
        return [CCHud msg:LS(@"图片不能为空")];
    }
    self.model.account = APP.user.account;
    [JobTool update:self.model complete:^(BOOL success) {
        [self backBtnAction];
    }];
}
-(void)backBtnAction{
    if (self.navigationController.viewControllers.count <= 1) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
- (Job *)model{
    if (!_model) {
        _model = [Job new];
    }
    return _model;
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    if (self.model) {
        [self.model.imgs addObject:data];
    }
    [self.tableView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < 5) {
        AddCell *cell = [tableView dequeueReusableCellWithIdentifier:[AddCell ID]];
        cell.title = self.array[indexPath.row];
        cell.model = self.model;
        return cell;
    }
    WS(self)
    ContentCell *cell = [tableView dequeueReusableCellWithIdentifier:[ContentCell ID]];
    cell.model = self.model;
    cell.block = ^{
        SheetViewController *sheetvc = [SheetViewController new];
        sheetvc.withCancel = NO;
        sheetvc.array = @[@"拍摄",@"相册",@"取消"];
        WS(sheetvc)
        sheetvc.block = ^(int index, NSString * _Nonnull text) {
            if ([text isEqualToString:LS(@"取消")]) {
                return [weaksheetvc dismissViewControllerAnimated:NO completion:nil];
            }
            NSString *mediaType = AVMediaTypeVideo; //读取媒体类型
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType]; //读取设备授权状态
            if (authStatus == AVAuthorizationStatusNotDetermined || authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) { // 授权受阻
                UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:LS(@"是否开启相机访问权限？")
                                                                                  message:nil
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *OFF = [UIAlertAction actionWithTitle:LS(@"取消") style:UIAlertActionStyleDefault handler:nil];
                UIAlertAction *ON = [UIAlertAction actionWithTitle:LS(@"确定") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { // 设置权限
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                            // do something
                        }];
                    }
                }];
                [alterCon addAction:OFF];
                [alterCon addAction:ON];
                [self presentViewController:alterCon animated:YES completion:nil];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [CCHud startHud];
                });
                UIImagePickerController *vc = [UIImagePickerController new];
                vc.delegate = weakself;
                vc.allowsEditing = YES;
                vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
                vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [weakself presentViewController:vc animated:YES completion:^{
                    [CCHud stopHud];
                }];
            }
        };
        [weakself presentViewController:sheetvc animated:NO completion:nil];
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(self)
    NSString * title = indexPath.row < self.array.count? self.array[indexPath.row] : @"";
    if ([title isEqualToString:@"植物"]) {
    }else if ([title isEqualToString:@"数量"]){
    }else if ([title isEqualToString:@"记农事"]){
        NongViewController *vc = [NongViewController new];
        vc.model = self.model;
        vc.block = ^{
            [weakself.tableView reloadData];
        };
        [self push:vc :YES];
    }else if ([title isEqualToString:@"简介信息"]){
        InputViewController *vc = [InputViewController new];
        vc.titlelbl.text = LS(@"简介信息");
        vc.input.placeholder = LS(@"请输入");
        vc.input.font = [UIFont systemFontOfSize:16];
        vc.input.placeHexColor = @"#999999";
        vc.input.bgHexColor = @"#E8F1EC";
        vc.block = ^(NSString * _Nonnull string) {
            weakself.model.plantDetail = string;
            [weakself.tableView reloadData];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if ([title isEqualToString:@"种植时间"]){
        JZBDateViewController *vc = [JZBDateViewController new];
        vc.stamp = [[NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"] intValue];
        vc.selectBlock = ^(int stamp) {
            weakself.model.stamp = stamp;
            [weakself.tableView reloadData];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return  0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
}
@end
